package com.iwhalecloud.bss.kite.cucc.web.controller.template;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.accept.in.AcceptRequestInDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProductModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.SceneVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ICuccSceneTemplateService;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.operate.ICuccOperateShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.query.ICuccQueryShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccSceneTemplateVo;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.even.GroupProdAttrEvent;
import com.iwhalecloud.bss.kite.cucc.web.controller.scene.SceneController;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.scene.service.operate.OperateExtParameterService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.vo.PageNavigationVO;
import com.iwhalecloud.bss.kite.web.service.scene.ISceneService;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.common.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <Description> 新装场景模版 <br>
 *
 * @author pan.dan<br>
 * @version 1.0<br>
 */
@RestController("cuccSceneTemplate")
@RequestMapping("/cuccSceneTemplate")
@Api(tags = {"/cuccSceneTemplate - 新装场景模版"
})
public class CuccSceneTemplateController {
    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    ICuccSceneTemplateService cuccSceneTemplateService;

    @Autowired
    private ISceneService sceneService;

    @Autowired
    private ICuccOperateShoppingCartService operateShoppingCartService;

    @Autowired
    private ICuccQueryShoppingCartService queryShoppingCartService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private ApplicationContext applicationContext;

    @ApiOperation(value = "保存新装场景模版")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = true),
        @ApiImplicitParam(name = "templName", value = "场景模版名称", required = true),
        @ApiImplicitParam(name = "sceneTemplId", value = "场景模版id", required = false)})
    @PostMapping(value = "/saveTemplate")
    public DataResult<String> saveTemplate(@RequestParam String sceneInstId, @RequestParam String templName, String sceneTemplId) {
        if (StringUtil.isEmpty(sceneTemplId)) {
            sceneTemplId  = cuccSceneTemplateService.saveTemplate(sceneInstId, templName);
        }
        else {
            sceneTemplId = cuccSceneTemplateService.updateTemplate(sceneInstId, templName, sceneTemplId);
        }

        DataResult<String> result = new DataResult<>();
        if (StringUtil.isEmpty(sceneTemplId)) {
            result.setResultCode("1");
            result.setResultMsg("模版保存失败！");
            result.setResultObject(null);
            return result;
        }
        result.setResultCode(ErrorConsts.SUCCESS.getCode());
        result.setResultMsg("模版保存成功！");
        result.setResultObject(sceneTemplId);
        return result;
    }

    @ApiOperation(value = "删除新装场景模版")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneTemplId", value = "场景模版id", required = true)})
    @PostMapping(value = "/deleteTemplate")
    public DataResult<Boolean> deleteTemplate(@RequestParam String sceneTemplId) {
        boolean deleteFlag = cuccSceneTemplateService.deleteTemplate(sceneTemplId);

        DataResult<Boolean> result = new DataResult<>();
        if (!deleteFlag) {
            result.setResultCode("1");
            result.setResultMsg("模版删除失败！");
            result.setResultObject(false);
            return result;
        }
        result.setResultCode(ErrorConsts.SUCCESS.getCode());
        result.setResultMsg("模版删除成功！");
        result.setResultObject(true);
        return result;
    }

//    @ApiOperation(value = "根据工号获取所有模版")
//    @ApiImplicitParams({@ApiImplicitParam(name = "staffId", value = "员工id", required = true),
//        @ApiImplicitParam(name = "pageSize", value = "每页内容数量", required = true),
//        @ApiImplicitParam(name = "pageIndex", value = "页码", required = true)})
//    @GetMapping(value = "/listSceneTempl")
//    public DataResult<PageInfo<CuccSceneTemplateVo>> listSceneTempl(@RequestParam String staffId, @RequestParam Integer pageSize, @RequestParam Integer pageIndex) {
//        PageInfo<CuccSceneTemplateVo> list = cuccSceneTemplateService.listSceneTempl(staffId, pageSize, pageIndex);
//        DataResult<PageInfo<CuccSceneTemplateVo>> result = new DataResult<>();
//        result.setResultCode(ErrorConsts.SUCCESS.getCode());
//        result.setResultObject(list);
//        return result;
//    }

    @ApiOperation(value = "根据场景id获取属性模版")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = true)})
    @GetMapping(value = "/listAttrTempl")
    public DataResult<List<CuccSceneTemplateVo>> listAttrTempl(@RequestParam String sceneInstId) {
        String staffId = ContextUtil.getUserId().toString();
        List<CuccSceneTemplateVo> list = cuccSceneTemplateService.listAttrTempl(staffId, sceneInstId);
        DataResult<List<CuccSceneTemplateVo>> result = new DataResult<>();
        result.setResultCode(ErrorConsts.SUCCESS.getCode());
        result.setResultObject(list);
        return result;
    }

//    @ApiOperation(value = "根据模版还原场景")
//    @ApiImplicitParams({@ApiImplicitParam(name = "sceneTemplId", value = "场景模版id", required = true)})
//    @GetMapping(value = "/getSceneTempl")
//    public DataResult<SceneVO> getSceneTempl(@RequestParam String sceneTemplId) {
//        Map<Object, String> params = new HashMap<>();
//        String custId = KiteWebContext.getContext().getCustId();
//        String custName = KiteWebContext.getContext().getCust().getCustName();
////        String custId = "1720082935396009";
////        String custName = "测试082904";
//        params.put("custId", custId);
//        params.put("custName", custName);
//        params.put("sceneTemplId", sceneTemplId);
//
//        //根据模版构建offerVO
//        CuccOfferInitVO offerVO = cuccSceneTemplateService.getTemplOfferVo(sceneTemplId);
//        String sceneInstId = sceneInitController.initOfferScene(offerVO).getResultObject();
//
//        cuccSceneTemplateService.updateSceneByTempl(sceneTemplId, sceneInstId); //根据模版还原场景
//
//        SceneVO scene = sceneController.createNewOfferSceneInst(offerVO.getOfferId(), sceneInstId, "1").getResultObject();
//
//        DataResult<SceneVO> result = new DataResult<>();
//        result.setResultCode(ErrorConsts.SUCCESS.getCode());
//        result.setResultObject(scene);
//        return result;
//    }

    @ApiOperation(value = "根据模版还原新装属性")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneTemplId", value = "场景模版id", required = true),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = true),
        @ApiImplicitParam(name = "offerId", value = "销售品id", required = true)})
    @GetMapping(value = "/getAttrTempl")
    public DataResult<SceneVO> getAttrTempl(@RequestParam String sceneTemplId, @RequestParam String sceneInstId, @RequestParam String offerId) {
        Boolean restul = SpringUtil.getBean(OperateExtParameterService.class).putExtParameter(sceneInstId, "isTempl", "T");
        cuccSceneTemplateService.updateSceneByTempl(sceneTemplId, sceneInstId);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId());
        PageNavigationVO pageNavigationVO = SpringUtil.getBean(SceneController.class)
            .getPageNavigation(sceneInst.getServiceOfferId(), OfferCache.get(offerInst.getOfferId()).getOfferType(),
                offerInst.getOfferId(), sceneInstId, null, null).getResultObject();
        String templateId = "1";
        if (pageNavigationVO != null) {
            templateId = pageNavigationVO.getTemplateId();
        }
        SceneVO scene = this.createNewOfferSceneInst(offerId, sceneInstId, templateId).getResultObject();

        DataResult<SceneVO> result = new DataResult<>();
        result.setResultCode(ErrorConsts.SUCCESS.getCode());
        result.setResultObject(scene);
        return result;
    }

    @ApiOperation(value = "模版重命名")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneTemplId", value = "场景模版id", required = true),
        @ApiImplicitParam(name = "newName", value = "新模版名称", required = true)})
    @GetMapping(value = "/renameTempl")
    public DataResult<Boolean> renameTempl(@RequestParam String sceneTemplId, @RequestParam String newName) {
        boolean renameFlag = cuccSceneTemplateService.renameTemplate(sceneTemplId, newName);

        DataResult<Boolean> result = new DataResult<>();
        if (!renameFlag) {
            result.setResultCode("1");
            result.setResultMsg("模版重命名失败！");
            result.setResultObject(false);
            return result;
        }
        result.setResultCode(ErrorConsts.SUCCESS.getCode());
        result.setResultMsg("模版重命名成功！");
        result.setResultObject(true);
        return result;
    }

    public DataResult<SceneVO> createNewOfferSceneInst(String offerId, String sceneInstId,String templateId) {
        KiteSceneInst sceneInst = this.querySceneInstService.getSceneInst(sceneInstId, KiteWebContext.getContext().getCustId());
        String serviceOfferId = sceneInst.getServiceOfferId();
        if (StringUtil.isBlank(offerId)) {
            if (InstType.PROD_INST.equals(sceneInst.getRootInstType())) {
                //基础销售品
                offerId = ProductCache.get(getSpecId(sceneInst)).getBaseOfferId();
            }
            else {
                offerId = getSpecId(sceneInst);
            }
        }
        AcceptRequestInDTO acceptRequest = new AcceptRequestInDTO();
        acceptRequest.setSceneInstId(sceneInstId).setSceneTemplateId(templateId).setOfferId(offerId)
            .setServiceOfferId(serviceOfferId);
        DataResult<SceneVO> sceneVoResult = sceneService.callEngine(acceptRequest);
        //发布属性分组处理事件
        SceneNewOfferSeneVO sceneVO = (SceneNewOfferSeneVO) sceneVoResult.getResultObject();
        List<ProductModuleVO> productModuleVOList = sceneVO.getSceneProductModuleVO().getProduct();
        Collections.reverse(productModuleVOList);
        GroupProdAttrEvent groupProdAttrEvent = new GroupProdAttrEvent(this, KiteWebContext.getContext().getCustId(),
            "");
        groupProdAttrEvent.setSceneInstId(sceneInstId);
        groupProdAttrEvent.setProductModuleVOList(productModuleVOList);
        applicationContext.publishEvent(groupProdAttrEvent);
        //发布状态修改事件-场景数据来源为订单中心的不需要保存购物车，不需要修改购物车状态
        String askSource = this.querySceneInstService.getSceneInst(sceneInstId).getAskSource();
        String saveCartFlag = querySceneInstService.getExtParameterValue(sceneInstId, "saveCart");
        if (!KiteStringUtils.equals(LocalKeyConsts.ASK_SOURCE_ORDER, askSource) && KiteStringUtils.isEmpty(saveCartFlag)) {
            this.operateSceneInstService.putExtParameter(sceneInstId, "saveCart", "saveCart");

            com.iwhalecloud.bss.kite.cucc.web.service.ISceneService cuccSceneService = SpringUtil.getBean(com.iwhalecloud.bss.kite.cucc.web.service.ISceneService.class);
            cuccSceneService.cacheShoppingCartGroup(sceneInstId, sceneInst.getCartId());
        }
        return sceneVoResult;
    }

    /**
     * 获取规格标识
     *
     * @return
     */
    private String getSpecId(KiteSceneInst kiteSceneInst) {
        KiteOfferInst offerInst = querySceneInstService
            .getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId());

        if (Objects.nonNull(offerInst)) {
            return offerInst.getSpecId();
        }
        else {
            return "";
        }

    }


    /**
     * 把当前场景添加到购物车，购物车分组状态是：待录入
     *
     * @param sceneInstId
     */
    private void cacheShoppingCartGroup(String sceneInstId, String cartId) {
        //this.sceneService.cacheShoppingCartGroup(sceneInstId, cartId);
        /*final String userId = ContextUtil.getUserId().toString();
        final String custId = KiteWebContext.getContext().getCustId();
        final String sessionId = ContextUtil.getHttpSessoinId();
        SimpleLoginInfo simpleLoginInfo = ContextUtil.getSimpleLoginInfo();
        if (KiteStringUtils.isEmpty(cartId)) {
            cartId = queryShoppingCartService.getShoppingCartId(userId, custId);
            KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
            kiteSceneInst.setCartId(cartId);
            operateSceneInstService.setSceneInst(kiteSceneInst);
        }
        String cartStr = cartId;
        CompletableFuture.runAsync(() -> {
            try {
                KiteTransactionUtils.beginTransaction();
                ContextUtil.setHttpSessoinId(sessionId);
                // 兼容接口调用
                ContextUtil.putSimpleLoginInfo2ThreadLocal(simpleLoginInfo);
                operateShoppingCartService
                    .cacheShoppingCartGroup(ContextUtil.getSimpleLoginInfo(), sceneInstId, userId, custId,
                        KeyConsts.SHOPPING_CART_GROUP_STATUS_INPUT, cartStr);
            }
            catch (Exception e) {
                // e.printStackTrace();
            }
            finally {
                KiteTransactionUtils.commit();
                KiteTransactionUtils.remove();
                ContextUtil.removeThreadLocal();
            }

        });*/
    }
}
